#include "../Net_h/NetAsyncImp.h"
#include "../Error_h/error.h"
#include <QString>
#include <QTcpSocket>
#include <QDataStream>
#include <QHostAddress>
#include <QIODevice>

NetAsyncImp::NetAsyncImp(){
    _socket = new QTcpSocket();
    _msgFromServer  ="";
    connect(_socket,SIGNAL(readyRead()),
            this,SLOT(Read()));
    connect(_socket,SIGNAL(error(QAbstractSocket::SocketError)),
                     this,SLOT(ReadError(QAbstractSocket::SocketError)));
 //   connect(_socket,&QTcpSocket::disconnected,[](){qDebug()<< "disconnect" ;});

}

int NetAsyncImp::Connect(QString ip, QString port){
    qDebug()<<"准备连接服务器 IP："+ip+"Port:"+port;
    _socket->abort();
    _socket->connectToHost(ip, port.toInt());
    if(IsConnected()){
        qDebug()<<"连接服务器成功~";
        return NONE;
    }
    else return VOICE_SERVER_CONNECT_ERROR;
}

bool NetAsyncImp::IsConnected(){
    return _socket->waitForConnected(3000);
}

int NetAsyncImp::ReConnect(QString ip, QString port){

}

int NetAsyncImp::Send(QString content){

    QByteArray message;
    QDataStream out(&message,QIODevice::WriteOnly);
    out.setVersion(QDataStream::Qt_5_4);
    out<<content;
    qDebug() << "send:" << content;
    _socket->write(message);
    return NONE;
}

void NetAsyncImp::Read(){
    QDataStream in(_socket);
    in.setVersion(QDataStream::Qt_4_6);
//    //设置数据流版本，这里要和服务器端相同
//    if(_blockSize==0) //如果是刚开始接收数据
//    {
//       //判断接收的数据是否有两字节，也就是文件的大小信息
//       //如果有则保存到blockSize变量中，没有则返回，继续接收数据
//       if(_socket->bytesAvailable() < (int)sizeof(quint16)) return;
//       in >> _blockSize;
//    }
//    if(_socket->bytesAvailable() < _blockSize) return;
//    //如果没有得到全部的数据，则返回，继续接收数据
    in >> _msgFromServer;
    qDebug()<<"收到服务器数据："+_msgFromServer;

    InformNewMessage();
}

void NetAsyncImp::ReadError(QAbstractSocket::SocketError){
    _socket->disconnectFromHost();
    qDebug()<<"错误为："<< _socket->errorString();
}
